package petrochina.company.electric.ui.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.base.FragmentPagerAdapter;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.tencent.mmkv.MMKV;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import petrochina.company.electric.R;
import petrochina.company.electric.app.AppActivity;
import petrochina.company.electric.app.AppFragment;
import petrochina.company.electric.event.ManagerConfirmEvent;
import petrochina.company.electric.event.ManagerHandleTaskResultEvent;
import petrochina.company.electric.event.ManagerLogoutTipEvent;
import petrochina.company.electric.event.SendManagerWorkEvent;
import petrochina.company.electric.event.TaskStepStatusChangeEvent;
import petrochina.company.electric.http.api.BleDeviceListApi;
import petrochina.company.electric.http.api.LoginApi;
import petrochina.company.electric.http.model.HttpData;
import petrochina.company.electric.manager.ActivityManager;
import petrochina.company.electric.model.ArtificialRequestData;
import petrochina.company.electric.model.SocketMessageData;
import petrochina.company.electric.other.DoubleClickHelper;
import petrochina.company.electric.service.TaskWebSocketService;
import petrochina.company.electric.socket.WebSocketEvent;
import petrochina.company.electric.ui.adapter.NavigationAdapter;
import petrochina.company.electric.ui.fragment.ApplyFragment;
import petrochina.company.electric.ui.fragment.FillFragment;
import petrochina.company.electric.ui.fragment.MineFragment;
import petrochina.company.electric.ui.fragment.TaskFragment;

/**
 * desc   : 首页界面
 */
public final class HomeActivity extends AppActivity
        implements NavigationAdapter.OnNavigationListener {

    private static final String INTENT_KEY_IN_FRAGMENT_INDEX = "fragmentIndex";
    private static final String INTENT_KEY_IN_FRAGMENT_CLASS = "fragmentClass";

    private ViewPager mViewPager;
    private RecyclerView mNavigationView;

    private NavigationAdapter mNavigationAdapter;
    private FragmentPagerAdapter<AppFragment<?>> mPagerAdapter;

    private final int HEART_TIME_INTERVAL = 5 * 1000;
//    private TaskWebSocketService webSocketService;
    private MMKV mmkv;
    private Gson gson;
    private LoginApi.Bean loginData;

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (loginData != null && loginData.getId() != 0 && webSocketService != null) {
                    SocketMessageData data = new SocketMessageData(9, loginData.getId(), 0, "");
                    String json = gson.toJson(data);
                    webSocketService.send(json);
                    Log.d("websocket", "发送心跳包" + json);
                    sendEmptyMessageDelayed(1, HEART_TIME_INTERVAL);
                }
            }
        }
    };

    public static void start(Context context) {
        start(context, TaskFragment.class);
    }

    public static void start(Context context, Class<? extends AppFragment<?>> fragmentClass) {
        Intent intent = new Intent(context, HomeActivity.class);
        intent.putExtra(INTENT_KEY_IN_FRAGMENT_CLASS, fragmentClass);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_activity;
    }

    @Override
    protected void initView() {
        mmkv = MMKV.defaultMMKV();
        gson = new Gson();
        EventBus.getDefault().register(this);

        String dataJson = mmkv.getString("loginData", null);
        if (!TextUtils.isEmpty(dataJson)) {
            loginData = gson.fromJson(dataJson, LoginApi.Bean.class);
        }
        if (loginData == null) {
            LoginActivity.start(this);
            finish();
        }

        mViewPager = findViewById(R.id.vp_home_pager);
        mNavigationView = findViewById(R.id.rv_home_navigation);

        mNavigationAdapter = new NavigationAdapter(this);
        mPagerAdapter = new FragmentPagerAdapter<>(this);
        // 不同身份展示不同页卡
        if (loginData.getDutyType() == 1 || loginData.getDutyType() == 2) {
            mNavigationAdapter.addItem(new NavigationAdapter.MenuItem(getString(R.string.home_nav_task),
                    ContextCompat.getDrawable(this, R.drawable.home_task_selector)));
            mNavigationAdapter.addItem(new NavigationAdapter.MenuItem(getString(R.string.home_nav_apply),
                    ContextCompat.getDrawable(this, R.drawable.home_apply_selector)));
            mPagerAdapter.addFragment(TaskFragment.newInstance());
            mPagerAdapter.addFragment(ApplyFragment.newInstance());
        }
        if (loginData.getDutyType() == 1 || loginData.getDutyType() == 3) {
            mNavigationAdapter.addItem(new NavigationAdapter.MenuItem(getString(R.string.home_nav_fill),
                    ContextCompat.getDrawable(this, R.drawable.home_fill_selector)));
            mPagerAdapter.addFragment(FillFragment.newInstance());
        }
        mNavigationAdapter.addItem(new NavigationAdapter.MenuItem(getString(R.string.home_nav_me),
                ContextCompat.getDrawable(this, R.drawable.home_me_selector)));
        mPagerAdapter.addFragment(MineFragment.newInstance());

        mNavigationAdapter.setOnNavigationListener(this);
        mNavigationView.setAdapter(mNavigationAdapter);
        mViewPager.setAdapter(mPagerAdapter);


//        WebSocketClient.startRequest();
        bindService(new Intent(this, TaskWebSocketService.class), serviceConnection, BIND_AUTO_CREATE);
//        AppApplication.getInstance().startWebSocketService();
//        WebSocketService service = ((AppApplication)getApplication()).getWebSocketService();
//        JWebSocketClient client = service.client;
//        boolean isOpen = client.isOpen();
//        if (AppApplication.getInstance().getWebSocketService() != null &&
//                AppApplication.getInstance().getWebSocketService().client != null && AppApplication.getInstance().getWebSocketService().client.isOpen()) {
//            AppApplication.getInstance().getWebSocketService().sendMsg("123123123");
//        } else {
//            Log.e("webSocket", "WebSocket连接已断开");
//        }
    }

    @Override
    protected void initData() {
        onNewIntent(getIntent());
        loadBleDevicesList();
//        MessageDialogActivity.start(this);
    }

    /**
     * 加载设备列表并本地持久化
     */
    private void loadBleDevicesList() {
        EasyHttp.get(this)
                .api(new BleDeviceListApi())
                .request(new HttpCallback<HttpData<List<BleDeviceListApi.Bean>>>(this) {

                    @Override
                    public void onSucceed(HttpData<List<BleDeviceListApi.Bean>> result) {
                        Gson gson = new Gson();
                        // 接地极
                        List<BleDeviceListApi.Bean> bleDevices2List = new ArrayList<>();
                        // 验电棒
                        List<BleDeviceListApi.Bean> bleDevices3List = new ArrayList<>();
                        // 蓝牙锁
                        List<BleDeviceListApi.Bean> bleDevices4List = new ArrayList<>();
                        for (int i = 0; i < result.getData().size(); i++) {
                            BleDeviceListApi.Bean data = result.getData().get(i);
                            if (data.getDevType() == 2) {
                                bleDevices2List.add(data);
                            } else if (data.getDevType() == 3) {
                                bleDevices3List.add(data);
                            } else if (data.getDevType() == 4) {
                                bleDevices4List.add(data);
                            }
                        }
                        String data2Json = gson.toJson(bleDevices2List);
                        String data3Json = gson.toJson(bleDevices3List);
                        String data4Json = gson.toJson(bleDevices4List);
                        MMKV mmkv = MMKV.defaultMMKV();
                        // 列表转换为json通过MMKV保存持久化
                        if (bleDevices2List.size() > 0) {
                            mmkv.putString("bleDevices2Json", data2Json);
                        }
                        if (bleDevices3List.size() > 0) {
                            mmkv.putString("bleDevices3Json", data3Json);
                        }
                        if (bleDevices4List.size() > 0) {
                            mmkv.putString("bleDevices4Json", data4Json);
                        }
                    }
                });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        switchFragment(mPagerAdapter.getFragmentIndex(getSerializable(INTENT_KEY_IN_FRAGMENT_CLASS)));
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        // 保存当前 Fragment 索引位置
        outState.putInt(INTENT_KEY_IN_FRAGMENT_INDEX, mViewPager.getCurrentItem());
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        // 恢复当前 Fragment 索引位置
        switchFragment(savedInstanceState.getInt(INTENT_KEY_IN_FRAGMENT_INDEX));
    }

    private void switchFragment(int fragmentIndex) {
        if (fragmentIndex == -1) {
            return;
        }
        mViewPager.setCurrentItem(fragmentIndex);
        mNavigationAdapter.setSelectedPosition(fragmentIndex);
//        switch (fragmentIndex) {
//            case 0:
//            case 1:
//            case 2:
//            case 3:
//                mViewPager.setCurrentItem(fragmentIndex);
//                mNavigationAdapter.setSelectedPosition(fragmentIndex);
//                break;
//            default:
//                break;
//        }
    }

    /**
     * {@link NavigationAdapter.OnNavigationListener}
     */

    @Override
    public boolean onNavigationItemSelected(int position) {
        if (position < mViewPager.getChildCount()) {
            mViewPager.setCurrentItem(position);
            return true;
        } else {
            return false;
        }
//        switch (position) {
//            case 0:
//            case 1:
//            case 2:
//            case 3:
//                mViewPager.setCurrentItem(position);
//                return true;
//            default:
//                return false;
//        }
    }

    @NonNull
    @Override
    protected ImmersionBar createStatusBarConfig() {
        return super.createStatusBarConfig()
                // 指定导航栏背景颜色
                .navigationBarColor(R.color.white);
    }

    @Override
    public void onBackPressed() {
        if (!DoubleClickHelper.isOnDoubleClick()) {
            toast(R.string.home_exit_hint);
            return;
        }

        // 移动到上一个任务栈，避免侧滑引起的不良反应
        moveTaskToBack(false);
        postDelayed(() -> {
            // 进行内存优化，销毁掉所有的界面
            ActivityManager.getInstance().finishAllActivities();
            // 销毁进程（注意：调用此 API 可能导致当前 Activity onDestroy 方法无法正常回调）
            // System.exit(0);
        }, 300);

    }

//    private void sendPersonHelp(){
//        if (loginData != null && loginData.getId() != 0 && webSocketService != null) {
//            SocketMessageData data = new SocketMessageData(2, loginData.getId(), 9, "");
//            String json = gson.toJson(data);
//            webSocketService.send(json);
//        }
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WebSocketEvent event) {
        if (event != null) {
//            Log.e("webSocket", "接收消息内容：" + event.getMessage());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(SendManagerWorkEvent event) {
        if (event != null) {
//            Log.e("webSocket", "接收消息内容：" + event.getData());
            String eventStr = gson.toJson(event);
            if (webSocketCallback != null) {
                webSocketService.send(eventStr);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ManagerHandleTaskResultEvent event) {
        if (event != null) {
//            Log.e("webSocket", "接收消息内容：" + event.getData());
            String eventStr = gson.toJson(event);
            if (webSocketCallback != null) {
                webSocketService.send(eventStr);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TaskStepStatusChangeEvent event) {
        if (event != null) {
//            Log.e("webSocket", "接收消息内容：" + event.getData());
            String eventStr = gson.toJson(event);
            if (webSocketCallback != null) {
                webSocketService.send(eventStr);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
        mHandler.removeCallbacksAndMessages(null);
        EventBus.getDefault().unregister(this);
        mViewPager.setAdapter(null);
        mNavigationView.setAdapter(null);
        mNavigationAdapter.setOnNavigationListener(null);
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            webSocketService = ((TaskWebSocketService.LocalBinder) service).getService();
            webSocketService.setWebSocketCallback(webSocketCallback);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            webSocketService = null;
        }
    };

    private TaskWebSocketService.WebSocketCallback webSocketCallback = new TaskWebSocketService.WebSocketCallback() {
        @Override
        public void onMessage(final String text) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (webSocketService == null || TextUtils.isEmpty(text)) {
                        return;
                    }
                    SendManagerWorkEvent data = null;
                    try {
                        data = gson.fromJson(text, SendManagerWorkEvent.class);
                    } catch (JsonSyntaxException e) {
                    }
                    if (data != null) {
                        switch (data.getType()) {
                            case 1:
                                if (!TextUtils.isEmpty(data.getData())) {
                                    ArtificialRequestData detailData = null;
                                    try {
                                        detailData = gson.fromJson(data.getData(), ArtificialRequestData.class);
                                    } catch (JsonSyntaxException e) {
                                    }
                                    if (detailData != null) {
                                        MessageDialogActivity.start(HomeActivity.this, data.getData());
                                    }
                                }
                                break;
                            case 2:
                            case 3:
                                ManagerConfirmEvent confirmEvent = new ManagerConfirmEvent(data.getType(), data.getUserId(), data.getCheckUserId(), data.getData());
                                EventBus.getDefault().post(confirmEvent);
                                break;
                            case 4:
                                // 监管人员不在线
                                ManagerLogoutTipEvent logoutEvent = new ManagerLogoutTipEvent(data.getType(), data.getUserId(), data.getCheckUserId(), data.getData());
                                EventBus.getDefault().post(logoutEvent);
                                break;
                            case 6:
                                // 执行人不在线
                                ToastUtils.show(data.getData());
                                break;
                        }
                    }
//                    ToastUtils.show(text);
//                    tvMessage.setText(text);
                }
            });
        }

        @Override
        public void onOpen() {
            Log.d("websocket", "loginData = " + loginData.toString() + " webSocketService = " + webSocketService.toString());
            if (loginData != null && loginData.getId() != 0 && webSocketService != null) {
                SocketMessageData data = new SocketMessageData(0, loginData.getId(), 0, "");
                String json = gson.toJson(data);
                webSocketService.send(json);
            }
            if (mHandler != null) {
                mHandler.sendEmptyMessageDelayed(1, HEART_TIME_INTERVAL);
            }
        }

        @Override
        public void onClosed() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    ToastUtils.show("onClosed");
                }
            });
        }
    };
}